package com.example.dqnm.controller;

import com.example.dqnm.mapper.UserDao;
import com.example.dqnm.pojo.Shippingaddress;
import com.example.dqnm.pojo.User;
import com.example.dqnm.pojo.UserDefaultStore;
import com.example.dqnm.pojo.ajaxResult;
import com.example.dqnm.service.UserService;
import com.example.dqnm.utils.WechatUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RequiredArgsConstructor
@RestController
@RequestMapping("/user")
public class userController {
    @Autowired
    private UserService userService;

    @GetMapping("/login")
    // 返回生成token
    public ajaxResult<String> login(String code) {
        // 当前的登录状态
        String token = userService.login(code);
        return new ajaxResult<String>(token);
    }

    @GetMapping("/userInfo")
    public ajaxResult<User> getUserInfo() {
        //得到servlet中的request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String openid = request.getServletContext().getAttribute("openid").toString();
//        System.out.println(openid);
        User user = userService.getUserInfo(openid);
//        System.out.println("request.getAttribute得到数据："+request.getAttribute("getAttribute"));
//        System.out.println("request.getServletContext().getAttribute得到全局数据："+request.getServletContext().getAttribute("openid"));
        return new ajaxResult<User>(user);
    }

    // 修改用户信息
    @PostMapping("/setUserInfo")
    public ajaxResult<Boolean> updateUserInfo(@RequestBody User user) throws IOException {
//        System.out.println(user);
        Boolean flag = userService.updateUserInfo(user);
        return new ajaxResult<>(flag);
    }

    // 保存修改的头像
    @PostMapping("/upload-avatar")
    public ajaxResult<String> uploadAvatar(@RequestParam("avatar") MultipartFile avatar) {
        String pathfile = userService.uploadAvatar(avatar);
        return new ajaxResult<>(pathfile);
    }

    // 修改自己送到的默认地址
    @PostMapping("/setDefaultAddress")
    public ajaxResult<Boolean> setDefaultAddress(@RequestBody Shippingaddress shippingaddress) {
        Boolean aBoolean = userService.setDefaultShippingAddress(shippingaddress);
        return new ajaxResult<>(aBoolean);
    }

    // 修改自己的默认商铺
    @PostMapping("/setDefaultStore")
    public ajaxResult<Boolean> setDefaultStore(@RequestBody UserDefaultStore userDefaultStore) {
        Boolean aBoolean = userService.setDefaultStore(userDefaultStore);
        return new ajaxResult<>(aBoolean);
    }
}
